import {get} from './api'
import {getRequest} from './api'


export const initMenu = (router, store) => {
    if (store.state.length > 0) {
        return;
    }
    getRequest('/system/cfg/menus').then(data => {
        if (data) {
            let fmtRoutes = formatRoutes(data);
            //添加到路由
            router.addRoutes(fmtRoutes)
            // 数据存在vuex中
            store.commit('initRoutes', fmtRoutes)
        }
    })
}
export const formatRoutes = (routes) => {
    let fmtRoutes = [];
    routes.forEach(router => {
        let {
            path,
            component,
            name,
            iconCls,
            children,
        } = router;
        if (children && children instanceof Array) {
            children = formatRoutes(children)
        }
        let fmtRouter = {
            path: path,
            name: name,
            iconCls: iconCls,
            children: children,
            component(resolve) {
                if (component.startsWith('Home')){
                    require([`../views/`+ component +'.vue'], resolve);
                }
                else if (component.substring(0,4) != "Home"){
                    let compt = component.substring(0,3);
                    require([`../views/`+compt.toLowerCase() +`/`+ component +`.vue`], resolve)
                }
            }
        }
        fmtRoutes.push(fmtRouter)
    })
    return fmtRoutes;
}